/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.servlet;

import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import offset.nodes.client.model.UserRequest;
import offset.nodes.server.controller.AttributeConstants;
import offset.nodes.server.controller.RepositoryPlugIn;

/**
 *
 * @author Walter Lütgenau
 */
public abstract class AbstractRepositoryService implements ServiceContainer {
    HttpServletRequest request;
    HttpServletResponse response;
    MessageServlet servlet;

    protected Session getSession(UserRequest request) throws RepositoryException {
        Session session = null;

        /* The applet implementor shall decide, which request will be authenticated. So if a user request does not contain credentials
         * we will use the repository session stored in the servlet session.
         * That way, we can easily add authentication security to certain requests, for example to version updates, that need a user id
         * anyway.
         */
        if ( request.getUserName() == null || request.getUserName().length() == 0) {
            session = (Session) getRequest().getSession().getAttribute(AttributeConstants.ATT_REPOSITORY_SESSION);
            return session;
        }

        Repository repository = RepositoryPlugIn.getRepository();

        session = repository.login(
                new SimpleCredentials(request.getUserName(), request.getPassword().toCharArray()));

        return session;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    public MessageServlet getServlet() {
        return servlet;
    }

    public void setServlet(MessageServlet servlet) {
        this.servlet = servlet;
    }
}
